#include <stdio.h>
#include <stdlib.h>

#include "../../include/queue.h"
#include "../../include/list.h"

static void print_queue(const queue_t *queue)
{
	list_node_t *n;
	unsigned int idx = 0;
	
	fprintf(stdout, "queue size is %d\n", queue_size(queue));

	n = list_head(queue);
	while (idx < queue_size(queue))
	{
		fprintf(stdout, "queue[%d] == %d\n", idx, *(int *)list_data(n));
		n = list_next(n);
		idx++;
	}

	return;
}


int main(int argc, char *argv[])
{
	queue_t queue;
	unsigned int idx = 0;
	list_node_t *n;
	int *data;

	queue_init(&queue, free);
	fprintf(stdout, "enqueuing 10 elements\n");
	for (idx = 0; idx < 10; idx++)
	{
		data = (int *)malloc(sizeof(int));
		if (!data)
			return -1;

		*data = idx + 1;
		if (queue_enqueue(&queue, data))
			return -1;
	}

	print_queue(&queue);

	fprintf(stdout, "dequeuing 5 elements\n");
	for (idx = 0; idx < 5; idx++)
	{
		if (!queue_dequeue(&queue, (void **)&data))
			free(data);
		else
			return -1;
	}

	print_queue(&queue);

	fprintf(stdout, "enqueuing 100 and 200\n");

	if (!(data = (int *)malloc(sizeof(int))))
		return -1;
	*data = 100;

	if (queue_enqueue(&queue, data))
		return -1;

	if (!(data = (int *)malloc(sizeof(int))))
		return -1;
	*data = 200;
	
	if (queue_enqueue(&queue, data))
		return -1;

	print_queue(&queue);

	if (data = queue_peek(&queue))
		fprintf(stdout, "peeking at head element...Value == %d\n", *data);
	else
		fprintf(stdout, "peeking at head element...Value == NULL\n");

	print_queue(&queue);

	fprintf(stdout, "dequeuing all elements\n");
	while(queue_size(&queue))
	{
		if (!queue_dequeue(&queue, (void **)&data))
			free(data);
		else
			return -1;
	}

	print_queue(&queue);

	if (data = queue_peek(&queue))
		fprintf(stdout, "peeking at head element...Value == %d\n", *data);
	else
		fprintf(stdout, "peeking at head element...Value == NULL\n");


	fprintf(stdout, "destroying queue\n");
	queue_destroy(&queue);
		
	return 0;
}
